class Issue < ActiveRecord::Base
  #has_and_belongs_to_many :users

  has_many :units
  has_many :users, :through => :units
  has_many :reporter, :through => :units, :source => :user, :conditions => ["units.unit_role = ?", "reporter"]
  has_many :developer, :through => :units, :source => :user, :conditions => ["units.unit_role = ?", "developer"]

  has_many :logs

  has_many :taggings, :as => :taggable

  has_many :tags, :through => :taggings, :order => 'tags.created_at ASC'
  has_many :tester_tags, :through => :taggings, :source => :tag, :conditions => ["taggings.tag_from IS NULL"]
  #has_many :system_tags, :through => :taggings, :source => :tag, :conditions => ["taggings.tag_from = ?", "system"]
  #has_many :user_tags, :through => :taggings, :source => :tag, :conditions => ["taggings.tag_from = ?", "user"]

  belongs_to :project

  state_machine :state, :initial => :submitted do
    event :assign do
      transition :submitted => :assigned
    end

    event :working do
      transition [:assigned, :reopen] => :resolved, :resolved => :finished
    end

    event :hang_up do
      transition [:submitted, :assigned, :reopen] => :suspend
    end

    event :rework do
      transition [:finished, :resolved, :suspend] => :reopen
    end
  end

  def self.get_all_open_issues
    all(:conditions => ["state NOT IN (?)", ["resolved","finished"]])
  end

  def self.count_all_open_issues
    get_all_open_issues.size.to_s
  end

  def self.get_open_issues(issue_type)
    all(:conditions => ["priority = ? and state NOT IN (?)", "#{issue_type}" , ["resolved","finished"]])
  end

  def self.count_open_issues(issue_type)
    get_open_issues(issue_type).size.to_s
  end

  def self.count_unassign_issues
    c = 0
    all.each do |i|
      if i.developer == []
        c = c + 1
      end
    end
    c.to_s
  end

  def self.count_issues(issue_type)
    count(:all, :conditions => ["priority = ?", "#{issue_type}"]).to_s
  end

  def self.get_issues(issue_type, sort="")
    all(:conditions => ["priority = ?", "#{issue_type}"], :order => sort)
  end

end
